const Router = require('koa-router');
const { pool } = require('../config/db');
const { verifyToken, getTokenFromRequest } = require('../utils/auth');
const { v4: uuidv4 } = require('uuid');

const router = new Router({
  prefix: '/groups'
});

// 使用自定义的中间件，处理token验证
const groupAuthMiddleware = async (ctx, next) => {
  const token = getTokenFromRequest(ctx);
  
  if (!token) {
    ctx.status = 401;
    ctx.body = {
      errCode: 'TOKEN_REQUIRED',
      errMsg: '未提供token',
      data: null
    };
    return;
  }
  
  const verifyResult = verifyToken(token);
  
  if (!verifyResult.valid) {
    ctx.status = 401;
    ctx.body = {
      errCode: 'TOKEN_INVALID',
      errMsg: verifyResult.message,
      data: null
    };
    return;
  }
  
  // 从token中获取用户ID
  const userId = verifyResult.payload.userId;
  
  try {
    // 查询用户信息
    const [users] = await pool.execute(
      'SELECT * FROM users WHERE id = ?',
      [userId]
    );
    
    if (users.length === 0) {
      ctx.status = 401;
      ctx.body = {
        errCode: 'USER_NOT_FOUND',
        errMsg: '用户不存在',
        data: null
      };
      return;
    }
    
    // 将用户ID保存到ctx.state中
    ctx.state.userId = users[0].id;
    
    await next();
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      errCode: 'AUTH_FAILED',
      errMsg: '验证用户信息失败：' + error.message,
      data: null
    };
  }
};

// 为所有路由添加认证中间件
router.use(groupAuthMiddleware);

/**
 * 确保群组有所有必要的字段
 * @param {object} group 群组信息
 * @param {string} userId 用户ID
 * @param {boolean} isCreate 是否是创建操作
 * @returns {object} 完整的群组信息
 */
function ensureGroupFields(group, userId, isCreate = false) {
  // 基本字段
  return {
    name: isCreate ? (group.name || `群聊 ${Date.now().toString(36)}`) : group.name,
    members: group.members || [],
    create_time: group.createTime || Date.now(),
    update_time: Date.now(),
    user_id: userId // 群组创建者ID
  };
}

/**
 * 获取所有群组（包括用户创建的和参与的群组）
 * POST /groups/getAllGroups
 */
router.post('/getAllGroups', async (ctx) => {
  try {
    // 查询用户创建的群组或者用户是成员的群组
    const [groups] = await pool.execute(
      `SELECT * FROM chat_groups WHERE user_id = ? OR members LIKE ?`,
      [ctx.state.userId, `%"${ctx.state.userId}"%`]
    );
    
    // 将groups中的members JSON字符串转为数组，并进行驼峰命名转换
    const formattedGroups = groups.map(group => {
      let members = [];
      try {
        // 尝试解析JSON字符串
        if (group.members) {
          members = JSON.parse(group.members);
        }
      } catch (e) {
        console.error('解析成员列表失败:', e);
      }
      
      return {
        id: group.id,
        name: group.name,
        members: members,
        createTime: group.create_time,
        updateTime: group.update_time,
        userId: group.user_id
      };
    });
    
    ctx.body = {
      errCode: 0,
      errMsg: '获取群组列表成功',
      data: formattedGroups
    };
  } catch (error) {
    console.error('获取群组列表失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'GET_GROUPS_FAILED',
      errMsg: '获取群组列表失败：' + error.message,
      data: [] // 发生错误时返回空数组
    };
  }
});

/**
 * 根据ID获取群组
 * POST /groups/getGroupById
 */
router.post('/getGroupById', async (ctx) => {
  const { id } = ctx.request.body;
  
  // 参数校验
  if (!id) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '群组ID不能为空',
      data: null
    };
    return;
  }
  
  try {
    // 查询群组
    const [groups] = await pool.execute(
      `SELECT * FROM chat_groups WHERE id = ?`,
      [id]
    );
    
    if (groups.length > 0) {
      const group = groups[0];
      
      // 解析成员列表
      let members = [];
      try {
        if (group.members) {
          members = JSON.parse(group.members);
        }
      } catch (e) {
        console.error('解析成员列表失败:', e);
      }
      
      // 检查权限：用户是创建者或成员
      if (group.user_id === ctx.state.userId || members.includes(ctx.state.userId)) {
        // 转为驼峰命名
        const formattedGroup = {
          id: group.id,
          name: group.name,
          members: members,
          createTime: group.create_time,
          updateTime: group.update_time,
          userId: group.user_id
        };
        
        ctx.body = {
          errCode: 0,
          errMsg: '获取群组成功',
          data: formattedGroup
        };
      } else {
        // 无权访问，返回null
        ctx.status = 403;
        ctx.body = {
          errCode: 'PERMISSION_DENIED',
          errMsg: '无权访问该群组',
          data: null
        };
      }
    } else {
      ctx.status = 404;
      ctx.body = {
        errCode: 'GROUP_NOT_FOUND',
        errMsg: '未找到该群组',
        data: null
      };
    }
  } catch (error) {
    console.error('获取群组失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'GET_GROUP_FAILED',
      errMsg: '获取群组失败：' + error.message,
      data: null
    };
  }
});

/**
 * 创建群组
 * POST /groups/createGroup
 */
router.post('/createGroup', async (ctx) => {
  const { members } = ctx.request.body;
  const name = ctx.request.body.name || '新群组';
  
  try {
    // 创建群组
    const now = Date.now();
    const groupId = uuidv4();
    
    // 准备成员列表，确保包含创建者
    let memberList = [];
    if (members && Array.isArray(members) && members.length > 0) {
      memberList = [...new Set([...members, ctx.state.userId])]; // 去重并确保包含创建者
    } else {
      memberList = [ctx.state.userId];
    }
    
    // 将成员列表存储为JSON字符串
    const membersJson = JSON.stringify(memberList);
    
    await pool.execute(
      'INSERT INTO chat_groups (id, name, user_id, members, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?)',
      [groupId, name, ctx.state.userId, membersJson, now, now]
    );
    
    ctx.body = {
      errCode: 0,
      errMsg: '创建群组成功',
      data: {
        id: groupId,
        name,
        userId: ctx.state.userId,
        members: memberList,
        createTime: now,
        updateTime: now
      }
    };
  } catch (error) {
    console.error('创建群组失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'CREATE_GROUP_FAILED',
      errMsg: '创建群组失败：' + error.message,
      data: null
    };
  }
});

/**
 * 更新群组
 * POST /groups/updateGroup
 */
router.post('/updateGroup', async (ctx) => {
  const { group } = ctx.request.body;
  
  // 参数校验
  if (!group || !group.id) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '群组信息或ID不能为空'
    };
    return;
  }
  
  try {
    // 查询群组，确认权限
    const [groups] = await pool.execute('SELECT * FROM chat_groups WHERE id = ?', [group.id]);
    
    if (groups.length === 0) {
      ctx.status = 404;
      ctx.body = {
        errCode: 'GROUP_NOT_FOUND',
        errMsg: '未找到该群组'
      };
      return;
    }
    
    const existingGroup = groups[0];
    
    // 检查权限，只有创建者才能更新群组
    if (existingGroup.user_id !== ctx.state.userId) {
      ctx.status = 403;
      ctx.body = {
        errCode: 'PERMISSION_DENIED',
        errMsg: '只有群组创建者才能更新群组'
      };
      return;
    }
    
    // 解析现有成员列表
    let existingMembers = [];
    try {
      if (existingGroup.members) {
        existingMembers = JSON.parse(existingGroup.members);
      }
    } catch (e) {
      console.error('解析成员列表失败:', e);
    }
    
    // 使用现有数据或更新数据
    const name = group.name || existingGroup.name;
    
    // 处理成员列表更新
    let members = existingMembers;
    if (group.members) {
      // 确保创建者始终在成员列表中
      members = [...new Set([...group.members, ctx.state.userId])];
    }
    
    // 更新时间
    const updateTime = Date.now();
    
    // 更新群组
    await pool.execute(
      'UPDATE chat_groups SET name = ?, members = ?, update_time = ? WHERE id = ?',
      [name, JSON.stringify(members), updateTime, group.id]
    );
    
    // 转为驼峰命名返回给客户端
    const formattedGroup = {
      id: group.id,
      name: name,
      members: members,
      createTime: existingGroup.create_time,
      updateTime: updateTime,
      userId: existingGroup.user_id
    };
    
    ctx.body = {
      errCode: 0,
      errMsg: '更新群组成功',
      data: formattedGroup
    };
  } catch (error) {
    console.error('更新群组失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'UPDATE_GROUP_FAILED',
      errMsg: '更新群组失败：' + error.message
    };
  }
});

/**
 * 添加群组成员
 * POST /groups/addGroupMember
 */
router.post('/addGroupMember', async (ctx) => {
  const { groupId, memberId } = ctx.request.body;
  
  // 参数校验
  if (!groupId || !memberId) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '群组ID和成员ID不能为空'
    };
    return;
  }
  
  try {
    // 查询群组，确认权限
    const [groups] = await pool.execute('SELECT * FROM chat_groups WHERE id = ?', [groupId]);
    
    if (groups.length === 0) {
      ctx.status = 404;
      ctx.body = {
        errCode: 'GROUP_NOT_FOUND',
        errMsg: '未找到该群组'
      };
      return;
    }
    
    const group = groups[0];
    
    // 检查权限，只有创建者才能添加成员
    if (group.user_id !== ctx.state.userId) {
      ctx.status = 403;
      ctx.body = {
        errCode: 'PERMISSION_DENIED',
        errMsg: '只有群组创建者才能添加成员'
      };
      return;
    }
    
    // 解析现有成员列表
    let members = [];
    try {
      if (group.members) {
        members = JSON.parse(group.members);
      }
    } catch (e) {
      console.error('解析成员列表失败:', e);
      members = [];
    }
    
    // 检查成员是否已存在
    if (members.includes(memberId)) {
      ctx.body = {
        errCode: 0,
        errMsg: '该成员已在群组中',
        data: {
          success: true
        }
      };
      return;
    }
    
    // 添加成员
    members.push(memberId);
    const updateTime = Date.now();
    
    // 更新群组
    await pool.execute(
      'UPDATE chat_groups SET members = ?, update_time = ? WHERE id = ?',
      [JSON.stringify(members), updateTime, groupId]
    );
    
    ctx.body = {
      errCode: 0,
      errMsg: '添加成员成功',
      data: {
        success: true
      }
    };
  } catch (error) {
    console.error('添加成员失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'ADD_MEMBER_FAILED',
      errMsg: '添加成员失败：' + error.message
    };
  }
});

/**
 * 移除群组成员
 * POST /groups/removeGroupMember
 */
router.post('/removeGroupMember', async (ctx) => {
  const { groupId, memberId } = ctx.request.body;
  
  // 参数校验
  if (!groupId || !memberId) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '群组ID和成员ID不能为空'
    };
    return;
  }
  
  try {
    // 查询群组，确认权限
    const [groups] = await pool.execute('SELECT * FROM chat_groups WHERE id = ?', [groupId]);
    
    if (groups.length === 0) {
      ctx.status = 404;
      ctx.body = {
        errCode: 'GROUP_NOT_FOUND',
        errMsg: '未找到该群组'
      };
      return;
    }
    
    const group = groups[0];
    
    // 检查权限，只有创建者才能移除成员
    if (group.user_id !== ctx.state.userId) {
      ctx.status = 403;
      ctx.body = {
        errCode: 'PERMISSION_DENIED',
        errMsg: '只有群组创建者才能移除成员'
      };
      return;
    }
    
    // 不能移除创建者自己
    if (memberId === ctx.state.userId) {
      ctx.status = 400;
      ctx.body = {
        errCode: 'CANNOT_REMOVE_CREATOR',
        errMsg: '不能移除群组创建者'
      };
      return;
    }
    
    // 解析现有成员列表
    let members = [];
    try {
      if (group.members) {
        members = JSON.parse(group.members);
      }
    } catch (e) {
      console.error('解析成员列表失败:', e);
      members = [];
    }
    
    // 检查成员是否存在
    if (!members.includes(memberId)) {
      ctx.status = 404;
      ctx.body = {
        errCode: 'MEMBER_NOT_FOUND',
        errMsg: '该成员不在群组中',
        data: {
          success: false
        }
      };
      return;
    }
    
    // 移除成员
    members = members.filter(id => id !== memberId);
    const updateTime = Date.now();
    
    // 更新群组
    await pool.execute(
      'UPDATE chat_groups SET members = ?, update_time = ? WHERE id = ?',
      [JSON.stringify(members), updateTime, groupId]
    );
    
    ctx.body = {
      errCode: 0,
      errMsg: '移除成员成功',
      data: {
        success: true
      }
    };
  } catch (error) {
    console.error('移除成员失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'REMOVE_MEMBER_FAILED',
      errMsg: '移除成员失败：' + error.message
    };
  }
});

/**
 * 删除群组
 * POST /groups/deleteGroup
 */
router.post('/deleteGroup', async (ctx) => {
  const { id } = ctx.request.body;
  
  // 参数校验
  if (!id) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '群组ID不能为空'
    };
    return;
  }
  
  try {
    // 查询群组，确认权限
    const [groups] = await pool.execute('SELECT * FROM chat_groups WHERE id = ?', [id]);
    
    if (groups.length === 0) {
      ctx.status = 404;
      ctx.body = {
        errCode: 'GROUP_NOT_FOUND',
        errMsg: '未找到该群组'
      };
      return;
    }
    
    const group = groups[0];
    
    // 检查权限，只有创建者才能删除群组
    if (group.user_id !== ctx.state.userId) {
      ctx.status = 403;
      ctx.body = {
        errCode: 'PERMISSION_DENIED',
        errMsg: '只有群组创建者才能删除群组'
      };
      return;
    }
    
    // 直接删除群组
    await pool.execute('DELETE FROM chat_groups WHERE id = ?', [id]);
    
    ctx.body = {
      errCode: 0,
      errMsg: '删除群组成功',
      data: {
        success: true
      }
    };
  } catch (error) {
    console.error('删除群组失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'DELETE_GROUP_FAILED',
      errMsg: '删除群组失败：' + error.message
    };
  }
});

module.exports = router; 